<template>
    <div class="breadcrumb">
        <el-breadcrumb separator="/">
            <el-breadcrumb-item
                ><router-link replace to="/"
                    >面板</router-link
                ></el-breadcrumb-item
            >
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        </el-breadcrumb>
        <el-divider />
        <el-button
            class="btn-add"
            plain
            type="danger"
            @click="adddrawer.show = true"
        >
            <el-icon><User /></el-icon>新增用户
        </el-button>
    </div>
    <div class="wrapper users">
        <el-table
            :data="list"
            style="width: 100%"
            v-loading="loading"
            empty-text="没有数据"
            element-loading-text="数据加载中..."
        >
            <el-table-column label="用户">
                <template #default="scope">
                    <div class="user-info">
                        <div class="avatar">
                            <img
                                :src="
                                    scope.row.avatar ||
                                    `https://fu5.web.sdo.com/10088/201707/14999374196439.png`
                                "
                                alt=""
                            />
                        </div>
                        <div class="name">{{ scope.row.username }}</div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="角色">
                <template #default="scope">
                    <el-tag type="danger" v-if="scope.row.role == `admin`"
                        >管理员</el-tag
                    >
                    <el-tag type="primary" v-else>普通用户</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="注册日期" prop="createdAt" />
            <el-table-column label="最近登录" prop="lastLogin" />
            <el-table-column label="状态">
                <template #default="scope">
                    <el-tag v-if="scope.row.status == 0" type="success"
                        >已启用</el-tag
                    >
                    <el-tag type="danger" v-else>已禁用</el-tag>
                </template>
            </el-table-column>
            <el-table-column width="320">
                <template #header>
                    <el-row :gutter="6">
                        <el-col :span="18">
                            <el-input
                                size="large"
                                clearable
                                placeholder="请输入搜索关键字"
                            />
                        </el-col>
                        <el-col :span="6">
                            <el-button type="primary" size="large">
                                搜索
                            </el-button>
                        </el-col>
                    </el-row>
                </template>
                <template #default="scope">
                    <el-switch
                        size="large"
                        style="margin-right: 10px"
                        v-model="scope.row.status"
                        inline-prompt
                        active-value="1"
                        inactive-value="0"
                        active-text="启用"
                        inactive-text="禁用"
                    ></el-switch>
                    <el-button type="primary"> 编辑 </el-button>
                    <el-button type="danger" @click="deleteUser(scope.row)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>
    <Teleport to="body">
        <!-- 用户删除 -->
        <el-dialog v-model="deletepop.show" width="400" center align-center>
            <h1 class="text-center">您确定要删除</h1>
            <div class="user-info flex-colomn">
                <div class="avatar">
                    <img
                        :src="
                            deletepop.user.avatar ||
                            `https://fu5.web.sdo.com/10088/201707/14999374196439.png`
                        "
                        alt=""
                    />
                </div>
                <div class="name">{{ deletepop.user.username }}</div>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="deletepop.show = false">取 消</el-button>
                    <el-button type="primary" @click="confirmDelete"
                        >确 定</el-button
                    >
                </span>
            </template>
        </el-dialog>
        <!-- 用户新增 -->
        <el-drawer
            v-model="adddrawer.show"
            size="400"
            class="add-drawer"
            :close-on-click-modal="false"
        >
            <template #title>
                <h1>
                    <el-icon><User /></el-icon> 新增用户
                </h1>
            </template>
            <el-form ref="addForm" label-width="80px">
                <el-form-item label="用户名">
                    <el-input
                        type="text"
                        placeholder="请输入用户名"
                        size="large"
                        v-model.trim="adddrawer.info.username"
                        :prefix-icon="User"
                    />
                </el-form-item>
                <el-form-item label="密码">
                    <el-input
                        type="password"
                        placeholder="请输入密码"
                        size="large"
                        v-model.trim="adddrawer.info.password"
                        :prefix-icon="Lock"
                    />
                </el-form-item>
                <el-form-item label="重复密码">
                    <el-input
                        type="password"
                        placeholder="请重新输入密码"
                        size="large"
                        v-model.trim="adddrawer.info.repeatpwd"
                        :prefix-icon="Lock"
                    />
                </el-form-item>
                <el-form-item label="头像">
                    <input
                        type="file"
                        accept="image/*"
                        ref="avatarRef"
                        style="display: none"
                        @change="uploadAvatar"
                    />
                    <div class="avatar" v-if="adddrawer.info.avatar">
                        <img :src="adddrawer.info.avatar" alt="" />
                        <div class="hover">
                            <el-icon
                                size="36"
                                class="icon"
                                @click="deleteAvatar"
                            >
                                <Delete />
                            </el-icon>
                        </div>
                    </div>
                    <div class="upload" v-else @click="openFile">
                        <el-icon size="36" class="icon" color="#999999">
                            <Plus />
                        </el-icon>
                    </div>
                </el-form-item>
                <el-divider />
                <el-form-item>
                    <div>
                        <el-button @click="adddrawer.show = false"
                            >取消</el-button
                        >
                        <el-button type="primary" @click="addUser"
                            >确定</el-button
                        >
                    </div>
                </el-form-item>
            </el-form>
        </el-drawer>
    </Teleport>
</template>

<script setup>
import { User, Lock, Plus, Delete } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { ref, reactive, onMounted } from "vue";
import { GetUsers, DeleteUser, AddUser, UploadPic } from "../../../../api";

const loading = ref(true);
const avatarRef = ref(null);
const list = ref([]);
const adddrawer = reactive({
    show: false,
    info: {}
});
const deletepop = reactive({
    show: false,
    user: {}
});

onMounted(() => {
    getUsers();
});

//  获取用户列表
const getUsers = async () => {
    loading.value = true;
    const res = await GetUsers();
    if (res && res.list.length) {
        list.value = res.list;
    }
    loading.value = false;
};

// 删除用户
const deleteUser = (user) => {
    deletepop.show = true;
    deletepop.user = user;
};
const confirmDelete = async () => {
    const res = await DeleteUser(deletepop.user._id);
    if (res) {
        list.value = list.value.filter(
            (item) => item._id != deletepop.user._id
        );
        ElMessage.success("删除成功");
        deletepop.show = false;
    }
};

// 打开文件框
const openFile = () => {
    avatarRef.value.click();
};
const uploadAvatar = async (e) => {
    const file = e.target.files[0];
    if (!file) {
        return;
    }
    if (file.size > 1024 * 1024 * 5) {
        return ElMessage.error("文件大小不能超过5M");
    }
    const formData = new FormData();
    formData.append("file", file);
    const res = await UploadPic(formData);
    if (res) {
        adddrawer.info.avatar = res.url;
        ElMessage.success("上传成功");
        avatarRef.value.value = "";
    }
};

const deleteAvatar = () => {
    adddrawer.info.avatar = "";
};
// 新增用户
const addUser = async () => {
    const { username, password, repeatpwd, avatar } = adddrawer.info;
    if (!username || !password || !repeatpwd || !avatar) {
        return ElMessage.error("请输入账号和密码及头像");
    }
    if (password.length < 6) {
        return ElMessage.error("密码长度不能小于6位");
    }
    if (!/[A-Z]/.test(password)) {
        return ElMessage.error("密码必须包含大写字母");
    }
    if (!/[0-9]/.test(password)) {
        return ElMessage.error("密码必须包含至少一个数字");
    }
    if (password !== repeatpwd) {
        return ElMessage.error("两次密码不一致");
    }
    const res = await AddUser(username, password, repeatpwd, avatar);
    if (res) {
        ElMessage.success("新增成功");
        list.value.unshift({
            _id: res._id,
            username,
            password,
            avatar,
            role: "user",
            status: 0
        });
        adddrawer.show = false;
    }
};
</script>

<style lang="scss" scoped>
.user-info {
    display: flex;
    align-items: center;
    &.flex-colomn {
        flex-direction: column;
        margin: 10px 0;
        .avatar {
            margin: 6px;
            width: 60px;
            height: 60px;
            position: relative;
        }
    }
    .avatar {
        width: 40px;
        height: 40px;
        display: block;
        border-radius: 50%;
        overflow: hidden;
        border: 1px solid rgba(0, 0, 0, 0.5);
        margin-right: 10px;
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: aquamarine;
        img {
            max-width: 100%;
            max-height: 100%;
        }
    }
}
.text-center {
    text-align: center;
}
.btn-add {
    position: absolute;
    z-index: 2;
    right: 0px;
    top: -8px;
}
.add-drawer {
    .avatar,
    .upload {
        width: 100px;
        height: 100px;
        display: flex;
        justify-content: center;
        align-items: center;
        overflow: hidden;
        border: 1px solid #ddd;
        border-radius: 4px;
        position: relative;
        img {
            width: 100%;
        }
        .hover {
            position: absolute;
            width: 100%;
            height: 100%;
            background-color: rgba(255, 255, 255, 0.5);
            display: flex;
            color: #ff0000;
            justify-content: center;
            align-items: center;
            opacity: 0;
            .icon {
                cursor: pointer;
            }
        }
        &:hover .hover {
            opacity: 1;
        }
    }
    .upload {
        cursor: pointer;
    }
}
</style>
